package com.tb.ClassSchedule;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

/**
 * Created by guich on 2016/8/26.
 */
public class LessonParser {

    public static String mainBodyHtml = "";
    public static String userNumber;

    public static Lesson[][] lessons;
    public static StringBuilder result = new StringBuilder();
    public static String getSrcUrl = "";


    public static void parse(String mainHtml, String number){
        mainBodyHtml = mainHtml;
        userNumber = number;

        Document     doc   = Jsoup.parse(mainBodyHtml);
        Elements     links = doc.select("a[href]");
        StringBuffer sb    = new StringBuffer();
        for (Element link : links) {
            //获取所要查询的URL,这里对应地址按钮的名字叫成绩查询
            if (link.text().equals("学生课表查询")) {
                sb.append(link.attr("href"));
            }
        }
        getSrcUrl = sb.toString();
        new Thread(new Runnable() {
            @Override
            public void run() {

                HttpURLConnection connection;

                try {
                    Log.d("getSrcUrl",getSrcUrl);
                    URL url = new URL(LoginActivity.HOST_URL + LoginActivity.RANDOM_URL + "/" + getSrcUrl);
                    Log.d("code", url.toString());

                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);

                    connection.addRequestProperty("Referer", "http://jwxt.hfnu.edu.cn/" + LoginActivity.RANDOM_URL + "/xs_main.aspx?xh=" + userNumber);
                    Log.d("Referer", "http://jwxt.hfnu.edu.cn/" + LoginActivity.RANDOM_URL + "/xs_main.aspx?xh=" + userNumber);
//                    connection.addRequestProperty("Referer", GETSCOREHOST + GETSCOREURL);
//                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//                    out.writeBytes("__VIEWSTATE=dDwtMTI2NjY4NjY5MTt0PHA8bDxzcWw7PjtsPCBzZWxlY3QgYS4qLCB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LTIwMTc7MjAxNS0yMDE2OzIwMTQtMjAxNTs+PjtsPGk8Mj47Pj47Oz47dDx0PDs7bDxpPDE+Oz4+Ozs+Oz4+Oz4+Oz5cBqwUZIwSFNMvYQT8W9qduKv6Gg==" +
//                            "&__EVENTTARGET=xqd" +
//                            "&__EVENTARGUMENT=" +
//                            "&xnd=2015-2016" +
//                            "&xqd=1");

                    InputStream in = connection.getInputStream();



                    Log.d("code", String.valueOf(connection.getResponseCode()));
                    Log.d("code", connection.getURL().toString());


                    BufferedReader reader = new BufferedReader(new
                            InputStreamReader(in, Charset.forName("gb2312")));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line).append("\n");
                    }

                    Log.d("response", response.toString());

                    getLessons(response.toString());

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }



    private static void getLessons(String parse) {

        lessons = new Lesson[11][7];

        Document doc = Jsoup.parse(parse);
        Elements trs = doc.select("table[id=Table1]").select("tr");

        int row = 0;  //记录节次
        for (Element tr : trs) {
            //不需要时间和早晨这两行
            if(tr.select("td").get(0).text().equals("时间") ||
                    tr.select("td").get(0).text().equals("早晨")){
                continue;
            }

            int col = 0;  //记录周次
            for (Element td : tr.select("td")) {
                String text    = td.text();

                //去掉非课程元素
                if(text.equals("上午") || text.equals("下午") || text.equals("晚上")){
                    continue;
                }
                if(text.startsWith("第") && text.endsWith("节")){
                    continue;
                }

                int rowspan;
                try{
                    rowspan = Integer.parseInt(td.attr("rowspan"));
                }catch (Exception e){
                    rowspan = 1;
                }

                //处理没课的情况
                if(text.length() == 1){
                    text = "—";
                }

                if(lessons[row][col] == null){
                    lessons[row][col] = new Lesson();
                    lessons[row][col].setName(text);
                    lessons[row][col].setRowSpan(rowspan);
                    if(rowspan != 1){
                        for(int i = 1 ; i < rowspan ; i ++){
                            lessons[row + i][col] = new Lesson("占位",1);
                        }
                    }
                }else{
                    //当前位置不是空的，那就看看是不是被占位
                    for(int j = 0 ; j < 7 ; j++){
                        //占位再看下一个位置是否被占
                        if(lessons[row][col + j] == null /*|| !lessons[row][col + j].getName().equals("占位")*/){
                            //有空位了,填上，退出
                            lessons[row][col + j] = new Lesson();
                            lessons[row][col + j].setName(text);
                            lessons[row][col + j].setRowSpan(rowspan);
                            if(rowspan != 1){
                                for(int k = 1 ; k < rowspan ; k ++){
                                    lessons[row + k][col] = new Lesson("占位",1);
                                }
                            }
                            break;
                        }
                    }
                }

                result.append(text).append(" : ").append(rowspan).append("    ");
                Log.i("xyz", text.length() + " : " + text);

                col++;
            }
            result.append("\n");
            row++;

        }

        for(int i = 0 ; i < 11 ; i++){
            StringBuilder sb = new StringBuilder();
            for(int j = 0 ; j < 7 ; j++) {
                sb.append(lessons[i][j].getName()).append("    ");
            }
            Log.d(i + "",sb.toString());
        }

        saveToDatabase();

    }

    private static void saveToDatabase() {
        //先清空数据库
        LessonDatabaseHelper dbHelper = new LessonDatabaseHelper(MainActivity.main, "Lessons.db", null, 1);
        SQLiteDatabase       db       = dbHelper.getWritableDatabase();

        db.execSQL("delete from Lesson");//清空数据
        db.execSQL("update sqlite_sequence SET seq = 0 where name ='Lesson'");//自增长ID为0

        //写入数据库
        for(int i = 0 ; i < lessons.length ; i ++){
            for(int j = 0 ; j < lessons[0].length ; j ++){

                if(lessons[i][j].getName().equals("占位") || lessons[i][j].getName().equals("—")){
                    continue;
                }

                //处理字符串，分离出名称，教室和教师，周次
                //计算机组成原理 周五第5,6节{第1-12周} 王大刚 逸夫楼A106* 计算机组成原理实验 周五第5,6节{第13-16周} 王大刚 躬行楼312
                //西方美术欣赏(慕课) {第3-13周|3节/周} 夏文玲 逸夫楼A101*
                String text = lessons[i][j].getName();
                //处理掉“ （调0008）”-->“”
                while (text.contains("(") && text.contains(")")){
                    int a = text.indexOf("(");
                    int b = text.indexOf(")",a);
                    //去掉前面的空格，b处的字符也要去掉，
                    String str = text.substring(a - 1,b + 1);
                    text = text.replace(str,"");
                }

                while (!text.equals("")){
                    //获取课程名
                    String str1 = text.substring(0,text.indexOf(' '));
                    text = text.substring(text.indexOf(' ') + 1);
                    lessons[i][j].setName(str1);
                    //获取周次
                    String str2 = text.substring(0,text.indexOf(' '));
                    text = text.substring(text.indexOf(' ') + 1);
                    int a = str2.indexOf("{第") + 2;
                    int b = str2.indexOf("-");
                    int c = str2.indexOf("周",b);
                    Log.d("a,b,c","" + a + " " + b + " " + c);
                    String startWeek = str2.substring(a,b);
                    String endWeek = str2.substring(b + 1,c);
                    lessons[i][j].setStartWeek(Integer.parseInt(startWeek));
                    lessons[i][j].setEndWeek(Integer.parseInt(endWeek));
                    //获取教师
                    String str3 = text.substring(0,text.indexOf(' '));
                    text = text.substring(text.indexOf(' ') + 1);
                    lessons[i][j].setTeacher(str3);
                    //获取地址
                    String str4;
                    if(text.contains(" ")){
                        str4 = text.substring(0,text.indexOf(' '));
                        text = text.substring(text.indexOf(' ') + 1);
                        lessons[i][j].setAddress(str4);
                    }else {
                        str4 = text;
                        text = "";
                        lessons[i][j].setAddress(str4);
                    }

                    ContentValues        values   = new ContentValues();
                    values.put("ClassName", lessons[i][j].getName());
                    values.put("WeekDay", j + 1);
                    values.put("StartSection", i + 1);
                    values.put("EndSection", i + lessons[i][j].getRowSpan());
                    values.put("StartWeek", lessons[i][j].getStartWeek());
                    values.put("EndWeek", lessons[i][j].getEndWeek());
                    values.put("TeacherName", lessons[i][j].getTeacher());
                    values.put("Address", lessons[i][j].getAddress());
                    db.insert("Lesson", null, values); //  插入第一条数据
                    values.clear();

                }

            }
        }

    }


}
